package com.heima.kafka.sample;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * 生产者
 */
@Slf4j
public class ProducerQuickStart {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.kafka的配置信息
        Properties properties = new Properties();
        //kafka的连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "47.97.69.121:9092");
        //发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG, 5);
        //消息数据压缩配置
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy");//snappy lz4 gzip
        //消息key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //消息value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        //2.生产者对象
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        //封装发送的消息
        ProducerRecord<String, String> record = new ProducerRecord<String, String>("itheima-topic", "100001", "hello kafka");

        //3.发送消息
        /**
         * 发送消息的2种方式:
         * ①同步发送
         * ②异步发送
         */
        //1.同步发送
        //同步发送消息耗时:2659
/*        long start1 = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            log.info("同步发送" + i);
            RecordMetadata recordMetadata = producer.send(record).get();
            System.out.println(recordMetadata.offset());
        }
        long end1 = System.currentTimeMillis();
        System.out.println("同步发送消息耗时:" + (end1 - start1));*/


        //2.异步发送
        //异步发送消息耗时:525
        long start2 = System.currentTimeMillis();
        for (int i = 0; i < 100; i++) {
            producer.send(record, new Callback() {
                @Override
                public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                    if (e != null) {
                        System.out.println("记录异常信息到日志中...");
                    }
                    System.out.println(recordMetadata.offset());
                }
            });
        }
        long end2 = System.currentTimeMillis();
        System.out.println("异步发送消息耗时:" + (end2 - start2));

        //4.关闭消息通道，必须关闭，否则消息发送不成功
        producer.close();
    }

}